package lzyc.pointsManagement.business.service.impl;

import lzyc.pointsManagement.business.attachment.convertor.AttachmentsConvertor;
import lzyc.pointsManagement.business.attachment.domain.Attachments;
import lzyc.pointsManagement.business.attachment.dto.AttachmentsDto;
import lzyc.pointsManagement.business.attachment.dto.AttachmentsType;
import lzyc.pointsManagement.business.attachment.mapper.AttachmentsMapper;
import lzyc.pointsManagement.business.service.AttachmentsService;
import lzyc.pointsManagement.common.response.ResponseMessage;
import lzyc.pointsManagement.common.response.ResponseMessageUtility;
import lzyc.pointsManagement.common.utils.StringUtils;
import lzyc.pointsManagement.common.utils.file.FileUtils;
import lzyc.pointsManagement.common.utils.uuid.IdUtils;
import lzyc.pointsManagement.system.service.ISysConfigService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author liuyuan
* @description 针对表【attachments】的数据库操作Service实现
* @createDate 2024-03-09 21:19:29
*/
@Service
public class AttachmentsServiceImpl implements AttachmentsService {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    ISysConfigService sysConfigService;
    AttachmentsMapper attachmentsMapper;

    public AttachmentsServiceImpl(ISysConfigService sysConfigService, AttachmentsMapper attachmentsMapper) {
        this.sysConfigService = sysConfigService;
        this.attachmentsMapper = attachmentsMapper;
    }

    public String getAttachmentPathByType(AttachmentsType attachmentType) {
        String type = attachmentType.name();
        return sysConfigService.selectConfigByKey("biz." + type + ".path");
    }

    @Override
    public void addAttachmentsDto(AttachmentsDto attachmentDto) {
        attachmentsMapper.addAttachments(AttachmentsConvertor.convertToEntity(attachmentDto));
    }

    @Override
    public void updateAttachmentsDto(AttachmentsDto attachments) {

    }

    @Override
    public void batchUpdateBizIds(List<String> ids, String bizId) {
        List<Attachments> attachments = attachmentsMapper.selectAttachmentByBizId(bizId);
        if (attachments != null && !attachments.isEmpty()) {
            batchUpdateBizIdFunc(attachments.stream().map(Attachments::getId).collect(Collectors.toList()), "");
        }
        batchUpdateBizIdFunc(ids, bizId);
    }

    @Override
    public void deleteAttachmentsDto(String id) {

    }

    @Override
    public ResponseMessage selectAttachmentsDtoById(String id) {
        ResponseMessage result;
        Attachments attachment = attachmentsMapper.selectAttachmentsById(id);
        if (attachment != null) {
            AttachmentsDto attachmentsDto = AttachmentsConvertor.convertToDto(attachment);
            String path = attachmentsDto.getPath();
            if (!StringUtils.isEmpty(path)) {
                try {
                    byte[] file = FileUtils.readFileToByteArray(Paths.get(path));
                    attachmentsDto.setFile(file);
                    result = ResponseMessageUtility.createSuccess();
                    result.setData(attachmentsDto);
                } catch (IOException e) {
                    result = ResponseMessageUtility.createError("附件不存在");
                }
            } else {
                result = ResponseMessageUtility.createError("附件路径为空");
            }
        } else {
            result = ResponseMessageUtility.createError("附件不存在");
        }
        return result;
    }

    @Override
    public List<AttachmentsDto> selectAttachmentsDtoList() {
        return null;
    }

    @Override
    public List<AttachmentsDto> selectAttachmentsDtoListByPage(int page, int size) {
        return null;
    }

    @Override
    public int countAttachmentsDtoList() {
        return 0;
    }

    @Override
    public AttachmentsDto getAttachmentsDtoById(String id) {
        Attachments attachments = attachmentsMapper.selectAttachmentsById(id);
        if (attachments != null) {
            return AttachmentsConvertor.convertToDto(attachments);
        }
        return new AttachmentsDto();
    }

    @Override
    public ResponseMessage getAttachmentsDtoByName(String name) {
        return null;
    }

    @Override
    public ResponseMessage getAttachmentsDtoByPath(String path) {
        return null;
    }

    @Override
    public ResponseMessage getAttachmentsDtoByType(String type) {
        return null;
    }

    public ResponseMessage fileUpload(MultipartFile file, AttachmentsDto dto) {
        if (file.isEmpty()) {
            return ResponseMessageUtility.createError("上传文件为空。");
        }
        ResponseMessage result;
        try {
            String pathStr = getAttachmentPathByType(dto.getType());
            createDirectory(pathStr);
            byte[] bytes = file.getBytes();
            String fileName = IdUtils.fastSimpleUUID() + "." + FileUtils.getFileExtension(file.getOriginalFilename());
            String url = pathStr + fileName;
            Path path = Paths.get(url);
            Files.write(path, bytes);
            dto.setName(fileName);
            dto.setPath(url);
            dto.setSize(bytes.length);
            this.addAttachmentsDto(dto);
            result = ResponseMessageUtility.createSuccess("上传成功。");
            result.setData(dto);
        } catch (IOException e) {
            result = ResponseMessageUtility.createError("上传失败。" + e.getMessage());
        }
        return result;
    }



    private void batchUpdateBizIdFunc(List<String> ids, String bizId) {
        try (SqlSession batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH)) {
            AttachmentsMapper mapper = batchSqlSession.getMapper(AttachmentsMapper.class);
            for (String id : ids) {
                mapper.updateBizId(bizId, id);
            }
            batchSqlSession.flushStatements(); // 执行所有更新操作
            batchSqlSession.commit(); // 提交事务
        }
    }

    private static void createDirectory(String directoryPath) {
        Path path = Paths.get(directoryPath);

        try {
            if (Files.notExists(path)) {
                Files.createDirectories(path);
                System.out.println("目录已创建: " + directoryPath);
            } else {
                System.out.println("目录已存在: " + directoryPath);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}




